<template>
  <div>
    <el-popover
      v-model="popShow"
      v-clickoutside="closePop"
      placement="bottom-start"
      trigger="manual"
      width="240"
    >
      <div class="myPop">
        <div class="popTitle">已录入小区</div>
        <div class="popList">
          <div
            v-for="(item, index) in community"
            :key="index"
            :class="item.id == community_id ? 'popBox activePop' : 'popBox'"
            @click.stop="choseCommunity(item)"
          >
            <div class="name">{{ item.community_name }}</div>
            <vab-icon
              v-if="item.is_allow_delete"
              class="deleteCommunity"
              icon="delete-back-2-line"
              @click.stop="deleteCommunity(item)"
            />
            <vab-icon
              v-else
              class="editCommunity"
              icon="edit-line"
              @click.stop="editCommunity(item)"
            />
          </div>
        </div>
        <div class="popFooter">
          没有你想要的小区？
          <span @click="AddCommunity">添加新小区</span>
        </div>
      </div>
      <el-input v-model="community_id" style="display: none" />
      <div
        :class="popShow ? 'popInput activePopInput' : 'popInput'"
        slot="reference"
        @click="changePop"
      >
        {{ community_name }}

        <i
          :class="
            popShow
              ? 'el-icon-arrow-down activeIcon icon'
              : 'el-icon-arrow-down icon'
          "
        ></i>
      </div>
    </el-popover>
    <el-dialog
      append-to-body
      :before-close="handleClose"
      destroy-on-close
      :title="title"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-form
        ref="communityForm"
        label-width="80px"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="小区名字" prop="community_name">
          <el-input
            v-model="form.community_name"
            placeholder="请输入小区名字"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getCommunityList,
    getCommunityDetail,
    addCommunity,
    editCommunity,
    deleteCommunity,
  } from '@/api/community'

  // 点击空白区域关闭popover
  const clickoutside = {
    bind(el, binding) {
      function documentHandler(e) {
        if (el.contains(e.target)) {
          return false
        }
        if (binding.expression) {
          binding.value(e)
        }
      }
      el.__vueClickOutside__ = documentHandler
      document.addEventListener('click', documentHandler)
    },
    update() {},
    unbind(el) {
      document.removeEventListener('click', el.__vueClickOutside__)
      delete el.__vueClickOutside__
    },
  }
  export default {
    name: 'SetCommunity',
    directives: { clickoutside },
    props: ['id'],
    data() {
      return {
        community: [],
        community_name: '',
        popShow: false,
        community_id: '',
        dialogVisible: false,
        title: '添加小区',
        form: {
          community_name: '',
        },
        rules: {
          community_name: [
            { required: true, trigger: 'blur', message: '请输入小区名字' },
          ],
        },
      }
    },
    watch: {
      id: {
        handler(newValue) {
          this.community_id = newValue
          this.getCommunity()
        },
        deep: true,
      },
    },
    mounted() {
      this.community_id = this.id
      this.getCommunity()
    },
    methods: {
      changePop() {
        this.popShow = !this.popShow
      },
      choseCommunity(item) {
        this.community_name = item.community_name
        this.community_id = item.id
        this.popShow = false
        this.$emit('get-data', this.community_id)
      },
      closePop() {
        this.popShow = false
      },
      editCommunity(item) {
        this.title = '编辑小区'
        this.form = item
        this.dialogVisible = true
      },
      AddCommunity() {
        this.title = '添加小区'
        this.form = {
          community_name: '',
        }
        this.dialogVisible = true
      },
      deleteCommunity(item) {
        console.log(item)
        this.$baseConfirm('你确定要删除此小区吗', null, async () => {
          const { data } = await deleteCommunity({ ids: item.id })
          if (data.is_success) {
            this.$baseMessage('删除成功', 'success', 'vab-hey-message-success')
            this.community_id = ''
            await this.getCommunity()
            this.$emit('get-data', this.community_id)
          }
        })
      },
      handleClose() {
        this.$refs['communityForm'].resetFields()
        this.form = this.$options.data.form
        this.dialogVisible = false
      },
      async getCommunity() {
        const { data } = await getCommunityList({})
        this.community = data
        if (this.community_id == '' || this.community_id == undefined) {
          this.community_id = this.community[0].id
          this.$emit('get-data', this.community_id)
        }
        this.getCommunityDetail(this.community_id)
      },
      async getCommunityDetail(id) {
        const { data } = await getCommunityDetail({ id })
        this.community_name = data.info.community_name
      },
      doUpdate() {
        this.$refs['communityForm'].validate(async (valid) => {
          if (valid) {
            if (this.title == '添加小区') {
              const { data } = await addCommunity(this.form)
              console.log(data)
              if (data.is_success) {
                this.$baseMessage(
                  '添加成功',
                  'success',
                  'vab-hey-message-success'
                )
                this.community_id = data.id
                this.$emit('get-data', this.community_id)
                this.getCommunity()
                this.dialogVisible = false
              }
            } else if (this.title == '编辑小区') {
              const { data } = await editCommunity(this.form)
              console.log(data)
              if (data.is_success) {
                this.$baseMessage(
                  '修改成功',
                  'success',
                  'vab-hey-message-success'
                )
                this.community_id = data.info.id
                this.$emit('get-data', this.community_id)
                this.getCommunity()
                this.dialogVisible = false
              }
            }
          }
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .myPop {
    display: block;
    font-size: 14px;
    .popTitle {
      margin-bottom: 6px;
    }
    .popList {
      .popBox {
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 32px;
        padding: 0 5px;
        transform: background 0.3s;
        &:hover {
          background: #f5f5f5;
        }
        &.activePop {
          background: #f0f7ff;
          .name {
            font-weight: 700;
          }
        }
        .editCommunity:hover {
          color: #1890ff;
        }
        .deleteCommunity:hover {
          color: red;
        }
      }
    }
    .popFooter {
      margin-top: 6px;
      span {
        cursor: pointer;
        color: #6898fc;
        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
  .popInput {
    width: 215px;
    height: 32px;
    padding: 0 30px 0 15px;
    border-radius: 2.5px;
    border: 1px solid #dcdfe6;
    position: relative;
    cursor: pointer;
    &:hover {
      border-color: #c0c4cc;
    }
    &.activePopInput {
      border-color: #1890ff;
    }
    .icon {
      width: 32px;
      height: 32px;
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      color: #c0c4cc;
      justify-content: center;
      align-items: center;
      transition: 0.3s;
      &.activeIcon {
        transform: rotate(-180deg);
      }
    }
  }
</style>
